package com.company.OfferGuide;

import org.omg.PortableInterceptor.INACTIVE;

import java.util.HashSet;
import java.util.Set;

public class 把字符串转换成整数 {

    public static void main(String[] args) {
        System.out.println(Long.MAX_VALUE);
        System.out.println(strToInt("9223372036854775808"));
    }

    public static int strToInt(String str) {
        long res = 0;
        Set<Character> set = new HashSet<>();

        for (int i = 0; i < 10; i++) {
            set.add((char)(i + '0'));
        }
        set.add('-');
        set.add('+');
        str = str.trim();
        boolean negetive = false;
        boolean first = false;
        for (int i = 0; i < str.length(); i++) {
            if (set.contains(str.charAt(i))) {
                if (str.charAt(i) == '-') {
                    if (first) return 0;
                    negetive = true;
                    first = true;
                    continue;
                } else if (str.charAt(i) == '+'){
                    if (first) return 0;
                    first = true;
                    continue;
                }
                res = res * 10 + (str.charAt(i) - '0');
                if (negetive) res = -res;
                if (res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
                if (res < Integer.MIN_VALUE) return Integer.MIN_VALUE;
            } else {
                break;
            }
        }

        if (negetive) res = -res;
        if (res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
        if (res < Integer.MIN_VALUE) return Integer.MIN_VALUE;

        return (int)res;
    }

}
